﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace BL
{
    public class cUDPConnectionHandler: cConnectionHandler
    {
        public delegate void DataReceivedListener(byte[] data);
        public event DataReceivedListener DataReceived;
        
        public UdpClient Client { get; set; }

        public bool IsListening { get; set; }

        public override void StartListening(int port)
        {
            Client = new UdpClient(port);

            IsListening = true;
            Thread thread = new Thread(new ThreadStart(this.ThreadedListening));
            thread.Start();
        }

        private void ThreadedListening()
        {
            IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
            while (IsListening)
            {
                if (Client.Available > 0)
                {
                    DataReceived(Client.Receive(ref remoteIpEndPoint));
                }
                Thread.Sleep(500);
            }
        }

        public override bool Connect(string IP, int port)
        {
            throw new NotSupportedException();
        }

        public override void Disconnect()
        {
            IsListening = false;
            Thread.Sleep(500);
            Client.Close();
        }
    }
}
